//! @Author: DengLibin
//! @Date: Create in 2023-10-20 13:39:18
//! @Description:

use std::{thread, time::Duration};

use tokio::runtime::Runtime;

pub async fn hello(i: i32){
    // tokio::time::sleep(Duration::from_millis(1000));
    
    println!("[{}]--[{:?}]hello world1--{}", current_thread_name(),  thread::current().id(), i);
}

pub  fn hello2(i: i32){
    // tokio::time::sleep(Duration::from_millis(1000));
    thread::sleep(Duration::from_secs(5)); //阻塞线程
    println!("[{}]--[{:?}]hello world2--{}", current_thread_name(),  thread::current().id(), i);
}
fn current_thread_name() -> String {
    let t = thread::current();
    let r = t.name();
    
    
    match r {
        Some(name) => {
            return name.into();
        }
        None => {
            return "-".into();
        }
    }
}
#[test]
pub fn run() {
    // let runtime = Runtime::new().unwrap();

    // 创建单一线程的runtime
    // let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
    // 创建带有线程池的runtime
//     Tokio 有两种线程。一种给异步任务的核心线程，一种是运行同步任务的阻塞线程。
// 核心线程池的数量和 CPU 核数相同，阻塞线程只有在需要的时候新建。
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2) // 工作核心线程数
        .thread_name("test-thread")
        
        .max_blocking_threads(10) //阻塞线程数 运行阻塞任务
        .enable_io() // 可在runtime中使用异步IO
        .enable_time() // 可在runtime中使用异步计时器(timer)
        .build() // 创建runtime
        .unwrap();
  
    let mut v1 = vec![];
   
    for i in 0..100 {
        let r1 = runtime.spawn(hello(i));
        //运行阻塞任务
        let r2 = runtime.spawn_blocking(move|| {
            hello2(i);
        });
      
        v1.push(r1);
        v1.push(r2);
    
        
    }


    runtime.block_on(async {
      for ele in v1 {
          let r = ele.await;
          match r {
              Ok(())=>{
                
              },
              Err(err)=>{
                println!("{}", err);
              }
          }
      }  


    });
    println!("完成..................");


    
}


#[test]
pub fn run2(){
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .max_blocking_threads(4)
        .build().unwrap();

    (0..14).for_each(|index| {
        runtime.spawn_blocking(move || {
            println!("[{}]hello tokio {}", thread::current().name().unwrap(), index);
            thread::sleep(Duration::from_secs(4));
        });
    });

    // 不立即关闭运行时，不然所有的线程都会运行任务，包括工作线程
    thread::sleep(Duration::from_secs(44));
    println!("[{}]", thread::current().name().unwrap());
    runtime.shutdown_timeout(Duration::from_secs(44));
   
}